<?php

namespace App\Http\Controllers\V1;

use App\Http\Requests\AfterSaleLogisticsRequest;
use App\Http\Requests\AfterSaleRequest;
use App\Http\Controllers\Controller;
use App\Models\AfterSale;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Scope\OnSaleScope;
use Illuminate\Support\Facades\Auth;

class AfterSaleController extends Controller
{
    // 售后列表
    public function afterSaleLists()
    {
       $data = AfterSale::with('detail')->where('user_id', Auth::id())->latest()->get();

       return $this->success($data);
    }

    // 售后详情
    public function afterSaleDetail($id)
    {
        $data = AfterSale::where('id', $id)->with('detail')->firstOrFail();
        $address = $data->detail->product->address;
        $data['address'] = $address;
        return $this->success($data);
    }

    // 填写物流号
    public function afterSaleLogistics(AfterSaleLogisticsRequest $request)
    {
        $data = AfterSale::where('id', $request->id)->firstOrFail();

        if ($data->refund_logistics_sn) {
            return $this->failed('您已经提交成功');
        }
        $res = $data->update([
            'refund_logistics_sn' => request()->logistics_code,
            'form_id' => request()->form_id,
            'status' => 1
        ]);
        if ($res) {
            return $this->success($data);
        }
        return $this->failed('提交失败');
    }

    // 判断是否有售后服务
    public function afterSaleServer()
    {
        $orderItemId = request()->item_id;

        if (AfterSale::where('order_item_id', $orderItemId)->where('user_id', Auth::id())->exists()) {
            return $this->failed('该商品您已经申请售后');
        }

        $items = OrderItem::where('id', $orderItemId)->firstOrFail();

        // 是否有退换货服务
        $product = $items->product()->withoutGlobalScope(OnSaleScope::class)->first();
        $services = $product->getOriginal('server_id');

        $order = $items->order()->first();
        $shipStatus = $order->getOriginal('ship_status');
        if (!in_array($shipStatus, [Order::SHIP_STATUS_RECEIVED])) {
            return $this->failed('当前订单状态不允许售后');
        }

        if (empty($services)) {
            return $this->failed('抱歉，您目前没有可发起的服务类型');
        }

        return $this->success([
            'item_id' => $items->id,
            'amount' => $items->amount,
            'product_sku_name' => $items->product_sku_name,
            'price' => $items->price,
            'title' => $items->product_title,
            'image' => $items->product_image,
            'services' => $services
        ]);
    }

    // 售后确认页面
    public function AfterSaleList()
    {
        $orderItemId = request()->item_id;

        if (AfterSale::where('order_item_id', $orderItemId)->where('user_id', Auth::id())->exists()) {
            return $this->failed('该商品您已经申请售后');
        }

        $items = OrderItem::where('id', $orderItemId)->firstOrFail();

        // 是否有退换货服务
        $product = $items->product()->withoutGlobalScope(OnSaleScope::class)->first();
        $services = $product->getOriginal('server_id');

        if (empty($services)) {
            return $this->failed('抱歉，您目前没有可发起等服务类型');
        }

        $order = $items->order()->first();
        $shipStatus = $order->getOriginal('ship_status');

        // 只允许 待收货 和 已完成才能申请退货
        if (in_array($shipStatus, [Order::SHIP_STATUS_RECEIVED])) {
            $note = '';
            // 获取抵扣金额
            $discount = $order->adjustments()->where('type', 'discount')->sum('amount');

            // 获取 已经申请的售后
            $afterSale = $order->afterSale()->get();

            //最大可退金额 = 退款金额 - 优惠总金额 / （订单原价 - 邮费） * 退款原价
            $i = ($order->original_price - $order->freight_price) * $items->price;
            if ($i > 0) {
                $bili = $discount / $i;
                if (floor($bili * 100) / 100 == 0) {
                    $refundPrice = $items->price;
                } else {
                    $refundPrice = $items->price - $bili;
                }
            } else {
                $refundPrice = $items->price;
            }
            if ($order->freight_price > 0 && $afterSale->isEmpty()) {
                $refundPrice = bcadd($refundPrice,$order->freight_price,2);
                $note .= '包含发货邮费¥'.$order->freight_price.';';
            }
            return $this->success([
                'item_id' => $items->id,
                'order_id' => $items->order_id,
                'product_id' => $items->product_id,
                'product_sku_name' => $items->product_sku_name,
                'amount' => $items->amount,
                'price' => $items->price,
                'title' => $items->product_title,
                'image' => $items->product_image,
                'refund_price' => $refundPrice,
                'note' => $note,
            ]);
        } else {
            return $this->failed('当前订单状态不允许售后');
        }
    }

    // 售后
    public function AfterSale(AfterSaleRequest $request)
    {
        $orderItemId = $request->item_id;

        if (AfterSale::where('order_item_id', $orderItemId)->where('user_id', Auth::id())->exists()) {
            return $this->failed('该商品您已经申请售后');
        }

        $items = OrderItem::with(['product' => function($query) {
            $query->withoutGlobalScope(OnSaleScope::class);
        }])->where('id', $orderItemId)->firstOrFail();

        $order = $items->order()->where('user_id', Auth::id())->first();

        if (is_null($order)) {
            return $this->failed('该商品订单不存在');
        }

        $shipStatus = $order->getOriginal('ship_status');

        // 只允许 待收货 和 已完成才能申请退货
        if (in_array($shipStatus, [Order::SHIP_STATUS_RECEIVED])) {
            // 获取抵扣金额
            $discount = $order->adjustments()->where('type', 'discount')->sum('amount');

            // 获取 已经申请的售后
            $afterSale = $order->afterSale()->get();

            //最大可退金额 = 退款金额 - 优惠总金额 / （订单原价 - 邮费） * 退款原价
            $i = ($order->original_price - $order->freight_price) * $items->price;
            if ($i > 0) {
                $bili = $discount / $i;
                if (floor($bili * 100) / 100 == 0) {
                    $refundPrice = $items->price;
                } else {
                    $refundPrice = $items->price - $bili;
                }
            } else {
                $refundPrice = $items->price;
            }
            if ($order->freight_price > 0 && $afterSale->isEmpty()) {
                $refundPrice = bcadd($refundPrice,$order->freight_price,2);
            }
            $res = AfterSale::create([
                'user_id' => Auth::id(),
                'order_item_id' => $orderItemId,
                'order_id' => $order->id,
                'type' => $request->type,
                'reason' => $request->reason,
                'image' => $request->image,
                'refund_price' => $refundPrice,
                'reject_reason' => '',
                'refund_logistics_sn' => '',
                'form_id' => $request->form_id
            ]);
            if ($res) {
                return $this->success(['id' => $res->id]);
            }
            return $this->failed('提交失败');
        } else {
            return $this->failed('当前订单状态不允许售后');
        }
    }
}
